package task5.file;


import task5.Util;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 文件服务器端
 */
public class FileServer {
    public static void main(String[] args){
        ServerSocket serverSocket = null;
        InputStream inputStream = null;
        FileOutputStream fileOutputStream = null;
        OutputStream outputStream = null;

        try {
            //创建服务
            serverSocket = new ServerSocket(9002);
            //监听客户端连接
            Socket socket = serverSocket.accept();
            //获取输入流
            inputStream= socket.getInputStream();
            //输出文件
            fileOutputStream= new FileOutputStream(new File("./src/task5/file/server.jpeg"));
            byte[] buffer = new byte[1024];
            int len ;
            while ((len=inputStream.read(buffer))!=-1){
                fileOutputStream.write(buffer,0,len);
            }

            //告诉客户端接收到了文件
            outputStream= socket.getOutputStream();
            outputStream.write("服务端收到了文件".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
            Util.close(outputStream,fileOutputStream,inputStream,serverSocket);
        }
    }
}
